home *** CD-ROM | disk | FTP | other *** search
/ Software Vault: The Gold Collection / Software Vault - The Gold Collection (American Databankers) (1993).ISO / cdr26 / netprog.zip / NETPROG.TAR / fd / myopen.c < prev    next >
C/C++ Source or Header  |  1989-12-17  |  1KB  |  52 lines

  1. /*
  2.  * Open a file, returning a file descriptor.
  3.  *
  4.  * This function is similar to the UNIX open() system call,
  5.  * however here we invoke another program to do the actual
  6.  * open(), to illustrate the passing of open files
  7.  * between processes.
  8.  */
  9.  
  10. int
  11. my_open(filename, mode)
  12. char    *filename;
  13. int    mode;
  14. {
  15.     int        fd, childpid, sfd[2], status;
  16.     char        argsfd[10], argmode[10];
  17.     extern int    errno;
  18.  
  19.     if (s_pipe(sfd) < 0)        /* create an unnamed stream pipe */
  20.         return(-1);        /* errno will be set */
  21.  
  22.     if ( (childpid = fork()) < 0)
  23.         err_sys("can't fork");
  24.  
  25.     else if (childpid == 0) {    /* child process */
  26.         close(sfd[0]);        /* close the end we don't use */
  27.         sprintf(argsfd, "%d", sfd[1]);
  28.         sprintf(argmode, "%d", mode);
  29.         if (execl("./openfile", "openfile", argsfd, filename,
  30.               argmode, (char *) 0) < 0)
  31.                 err_sys("can't execl");
  32.     }
  33.  
  34.     /* parent process - wait for the child's execl() to complete */
  35.  
  36.     close(sfd[1]);            /* close the end we don't use */
  37.     if (wait(&status) != childpid)
  38.         err_dump("wait error");
  39.     if ((status & 255) != 0)
  40.         err_dump("child did not exit");
  41.     status = (status >> 8) & 255;        /* child's exit() argument */
  42.     if (status == 0) {
  43.         fd = recvfile(sfd[0]);        /* all OK, receive fd */
  44.     } else {
  45.         errno = status;    /* error, set errno value from child's errno */
  46.         fd = -1;
  47.     }
  48.  
  49.     close(sfd[0]);        /* close the stream pipe */
  50.     return(fd);
  51. }
  52.